import BaseFrame from './BaseFrame';
import * as THREE from 'three';
import vertexShader from '@/shader/spriteRise/vert.glsl';
import fragmentShader from '@/shader/spriteRise/frag.glsl';
import gsap from 'gsap';
export default class SpriteRise extends BaseFrame {
	constructor() {
		super();
		this.meshes = [];
		this.params = { time: 0 };
		this.initScene();
	}
	initScene() {
		this.camera.position.set(0, 1, 5);
		// this.controls.target.set(0, 8, 0);
		// this.groundMesh.visible = false;
		const loader = new THREE.TextureLoader();
		const texture = loader.load('/img/texture/sprite_rise.png', () => {
			this.initGui();
			this.renderOnce();
		});
		texture.wrapS = THREE.RepeatWrapping;
		texture.wrapT = THREE.RepeatWrapping;
		this.shaderMaterial = new THREE.ShaderMaterial({
			uniforms: {
				//时间变量
				uTime: {
					value: 0,
				},
				//速度
				uSpeed: {
					value: 5,
				},
				//纹理
				uTexture: {
					value: texture,
				},
				//颜色
				uColor: {
					value: new THREE.Color(0x46c2f7),
				},
			},
			vertexShader: vertexShader,
			fragmentShader: fragmentShader,
			blending: THREE.AdditiveBlending,
			transparent: true,
			depthTest: false,
		});
		let originMesh = new THREE.Sprite(this.shaderMaterial);
		for (let i = 0; i < 10; i++) {
			const mesh = originMesh.clone();
			let angle = Math.random() * Math.PI * 2;
			let radio = Math.random() * 4;
			let initY = Math.random() * 5;
			mesh.position.set(radio * Math.cos(angle), initY, radio * Math.sin(angle));
			this.scene.add(mesh);
			this.meshes.push({
				mesh: mesh,
				initY: initY,
			});
		}
		gsap.fromTo(
			this.params,
			{ time: 0 },
			{
				time: 1000,
				duration: 3000,
				ease: 'linear',
				onUpdate: () => {
					this.meshes.forEach((item) => {
						item.mesh.position.y = ((this.params.time + item.initY) % 4) - 1;
					});
				},
			}
		);
	}
	initGui() {
		this.gui.add(this.shaderMaterial.uniforms.uSpeed, 'value').min(1).max(10).step(0.01).name('速度');
		this.gui.addColor(this.shaderMaterial.uniforms.uColor, 'value').name('颜色');
	}
	update() {
		if (this.shaderMaterial) {
			this.shaderMaterial.uniforms.uTime.value = this.clock.getElapsedTime();
		}
	}
}
